package com.example.jobback.service.recruiter.impl;

import com.example.jobback.mapper.CollectMapper;
import com.example.jobback.mapper.CompanyMapper;
import com.example.jobback.mapper.PositionMapper;
import com.example.jobback.mapper.RecruiterMapper;
import com.example.jobback.po.*;
import com.example.jobback.req.seeker.company.GetPageCompaniesReq;
import com.example.jobback.service.recruiter.RecruiterCommonService;
import com.example.jobback.service.recruiter.RecruiterCrossService;
import com.example.jobback.util.CACHEUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

import static com.example.jobback.util.ConstantsUtil.*;
import static com.example.jobback.util.RedisConstants.HOT_COMPANY_CITIES_KEY;
import static com.example.jobback.util.RedisConstants.HOT_POSITION_CITIES_KEY;

/**
 * @ClassName: RecruiterCrossServiceImpl
 * @Description:跨服务-招聘者接口实现类
 * @Author: lhb
 * @Date: 2025/7/12
 */
@Service
public class RecruiterCrossServiceImpl implements RecruiterCrossService {

    private final PositionMapper positionMapper;

    private final RecruiterMapper recruiterMapper;

    private final CACHEUtil cacheUtil;

    private final CompanyMapper companyMapper;

    private final RecruiterCommonService recruiterCommonService;

    public RecruiterCrossServiceImpl(PositionMapper positionMapper, RecruiterCommonService recruiterCommonService, RecruiterMapper recruiterMapper, CompanyMapper companyMapper, CACHEUtil cacheUtil) {
        this.positionMapper = positionMapper;
        this.recruiterCommonService = recruiterCommonService;
        this.recruiterMapper = recruiterMapper;
        this.companyMapper = companyMapper;
        this.cacheUtil = cacheUtil;
    }

    @Override
    public PageInfo<Position> getPositions(int page, int size, String content) {
        PageHelper.startPage(page, size);
        List<Position> positionList = positionMapper.getPositionsByPositionName(content);
        PageInfo<Position> positionPageInfo = new PageInfo<>(positionList);
        return positionPageInfo;
    }

    @Override
    public Position getPositionById(Long positionId) {
        return positionMapper.getPositionById(positionId);
    }

    @Override
    public Recruiter getRecruiterByUserId(Long userId) {
        return recruiterMapper.getRecruiterByUserId(userId);
    }

    @Override
    public List<String> getHotPositionCities() {
        int num = HOT_LOCATION_MIN_POSITIONS;
        return positionMapper.getHotCities(num);
    }

    @Override
    /**
     * @Description: 根据公司id获取公司信息
     * @param companyId
     * @return Company
     * @Author lhb
     * @CreateTime 2025/7/16 9:44
     */
    public Company getCompanyMessage(Long companyId) {
        return recruiterCommonService.getCompanyMessage(companyId);
    }

    /**
     * @Description: 获取指定招聘者发布的岗位
     * @param userId
     * @return List<Position>
     * @Author lhb
     * @CreateTime 2025/7/16 9:50
     */
    @Override
    public List<Position> getPositionsByUserId(Long userId) {
        return positionMapper.getPositionByUserId(userId);
    }

    /**
     * @Description: 根据userIds获取招聘者信息
     * @param recruiterUserIdList
     * @return List<Recruiter>
     * @Author lhb
     * @CreateTime 2025/7/17 11:36
     */
    @Override
    public List<Recruiter> getRecruiterByUserIds(List<Long> recruiterUserIdList) {
        return recruiterMapper.getRecruiterByUserIds(recruiterUserIdList);
    }

    /**
     * @Description: 根据positionIds获取职位信息
     * @param positionIdList
     * @return List<Position>
     * @Author lhb
     * @CreateTime 2025/7/17 11:37
     */
    @Override
    public List<Position> getPositionByIds(List<Long> positionIdList) {
        return positionMapper.getPositionByIds(positionIdList);
    }

    @Override
    public List<Company> getCompanyMessagesByIds(List<Long> companyIds) {
        return recruiterCommonService.getCompanyMessagesByIds(companyIds);
    }

    @Override
    public PageInfo<Company> getCompanies(GetPageCompaniesReq req) {
        int pageNum = req.getPageNum();
        int pageSize = req.getPageSize();
        Company company = new Company();
        BeanUtils.copyProperties(req, company);
        PageHelper.startPage(pageNum, pageSize);
        List<Company> companyList = companyMapper.searchPageCompanyList(company);
        //获取页的相关信息
        PageInfo<Company> companyPageInfo = new PageInfo<>(companyList);
        return companyPageInfo;
    }

    @Override
    public List<Recruiter> getRecruitersByCompanyId(Long companyId) {
        return recruiterMapper.getRecruitersByCompanyId(companyId);
    }

    @Override
    public List<Position> getPositionByCompanyId(Long companyId) {
        return positionMapper.getPositionByCompanyId(companyId);
    }

    @Override
    public List<String> getHotCompanyCities() {
        int num = HOT_LOCATION_MIN_COMPANIES;
        return companyMapper.getHotCities(num);
    }

    @Override
    public List<Company> smartRecommendCompanyList(Seeker seeker) {
        //根据行业和职位名称推荐企业所需的最小岗位数
        int smartCompanyMinPosition = SMART_COMPANY_MIN_POSITION;
        //启用热门推荐最小的企业数
        int smartStartMinCompany = SMART_START_MIN_COMPANY;
        // 智能推荐企业限制数
        int smartCompanyLimit = SMART_COMPANY_LIMIT;
        String expectedIndustry = seeker.getExpectedIndustry();
        String expectedPosition = seeker.getExpectedPosition();
        String location = seeker.getLocation();
        //如果用户未设置location，默认为空字符串，防止发生空异常
        if(Objects.isNull(location)) {
            location = "";
        }
        boolean isEmptyExpectedIndustry = StringUtils.isBlank(expectedIndustry);
        boolean isEmptyExpectedPosition = StringUtils.isBlank(expectedPosition);
        boolean isHotCity = cacheUtil.isMemberInSet(HOT_COMPANY_CITIES_KEY, location);
        Set<Long> companyIdSet = new HashSet<>();
        if(BooleanUtils.isFalse(isEmptyExpectedIndustry)) {
            //根据职位行业进行匹配公司id
            List<Long> companyIdList = positionMapper.smartRecommendComIdsByJobIndustry(expectedIndustry, smartCompanyMinPosition, location);
            companyIdSet.addAll(companyIdList);
        }
        if(BooleanUtils.isFalse(isEmptyExpectedPosition)) {
            //根据职位名称进行匹配公司id
            List<Long> companyIdList = positionMapper.smartRecommendComIdsByPositionName(expectedPosition, smartCompanyMinPosition, location);
            companyIdSet.addAll(companyIdList);
        }
        List<Long> interestCompanyIdList = new ArrayList<>(companyIdSet);
        List<Company> smartCompanyList = new ArrayList<>();
        if(companyIdSet.size() <= smartStartMinCompany) {
            //内容不足直接匹配
            smartCompanyList = companyMapper.smartRecommendCompany(smartCompanyLimit, location);
            //非热门城市，数量不足继续匹配
            if(BooleanUtils.isFalse(isHotCity)) {
                if(smartCompanyList.size() <= smartStartMinCompany) {
                    List<Company> smartCompanyAgainList = companyMapper.smartRecommendCompany(smartCompanyLimit, "");
                    smartCompanyList = mergeAndDeduplicate(smartCompanyList, smartCompanyAgainList);
                }
            }
        }
        List<Company> interestCompanyList = recruiterCommonService.getCompanyMessagesByIds(interestCompanyIdList);
        List<Company> companyList = mergeAndDeduplicate(interestCompanyList, smartCompanyList);
        return companyList;
    }

    @Override
    public Long getCompanyNum() {
        return companyMapper.getCompanyNum();
    }

    @Override
    public Long getActivePositions() {
        return positionMapper.getActivePositions();
    }


    /**
     * @Description: 合并并去重
     * @param list1
     * @param list2
     * @return List<Position>
     * @Author lhb
     * @CreateTime 2025/7/25 10:39
     */
    private List<Company> mergeAndDeduplicate(List<Company> list1, List<Company> list2) {
        Map<Long, Company> uniqueMap = new LinkedHashMap<>();
        for (Company c : list1) {
            uniqueMap.put(c.getCompanyId(), c);
        }
        for (Company c : list2) {
            uniqueMap.putIfAbsent(c.getCompanyId(), c);
        }
        return new ArrayList<>(uniqueMap.values());
    }


}
